package utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

/**
 * 公用帮助类
 * 
 */
@SuppressLint({ "SimpleDateFormat", "UseValueOf", })
public class EncodingUtil {
	/**
	 * 城市对应的目录和秘钥
	 * @param city
	 * @return
	 */
	public static String[] getCityIndex(String city){
		String[] strs = new String[3];
		if(city.equals("聚利")){ //0
			strs[0]="DF01";
			strs[1]="46";
			strs[2]="59";
		}else if(city.equals("福建")){//1
			strs[0]="DF02";
			strs[1]="28";
			strs[2]="59";
		}else if(city.equals("辽宁")){//2
			strs[0]="DF02";
			strs[1]="26";
			strs[2]="59";
		}else if(city.equals("浙江")){//3
			strs[0]="DF01";
			strs[1]="26";
			strs[2]="59";
		}else if(city.equals("四川")){//4
			strs[0]="DF01";
			strs[1]="26";
			strs[2]="59";
		}else if(city.equals("KT新")){//5
			strs[0]="DF01";
			strs[1]="28";
			strs[2]="39";
		}else if(city.equals("ITS")){//6
			strs[0]="DF01";
			strs[1]="28";
			strs[2]="39";
		}
		return strs;
	}
	
	/**
	 * 前补零
	 * @param value
	 * @param num
	 * @return
	 */
	public static String addzero(String value,int num){
		String context = value;
		for (int i = context.length(); i < num*2; i++) {
			context="0"+context;
		}
		return context;
	}
	/**
	 * 返回时间格式 20140113000000
	 * @param date
	 * @return
	 */
	public static String getThisDayDate(Calendar date) {
		String year = date.get(Calendar.YEAR) + "";
		// 月份转(不够用0补)
		String month = addZero((date.get(Calendar.MONTH) + 1) + "");
		// 日转8进制(不够用0补)
		String day = addZero(date.get(Calendar.DATE) + "");
		return year + month + day+"000000";
	}
	/**
	 * 返回时间格式 20140113101010
	 * @param date
	 * @return
	 */
	public static String getThisBCDDate(Calendar date) {
		String year = date.get(Calendar.YEAR) + "";
		// 月份转(不够用0补)
		String month = addZero((date.get(Calendar.MONTH) + 1) + "");
		// 日转8进制(不够用0补)
		String day = addZero(date.get(Calendar.DATE) + "");
		// 小时
		String hours = addZero(date.get(Calendar.HOUR) + "");
		// 分钟
		String minute = addZero(date.get(Calendar.MINUTE) + "");
		// 秒
		String seconds = addZero(date.get(Calendar.SECOND) + "");
		return year + month + day + hours + minute + seconds;
	}
	/**
	 * 返回时间格式 20140113121212
	 * 
	 * @param date
	 * @return
	 */
	public static String getThisDBDayDate(Calendar date) {
		String year = date.get(Calendar.YEAR) + "";
		// 月份转(不够用0补)
		String month = addZero((date.get(Calendar.MONTH) + 1) + "");
		// 日转8进制(不够用0补)
		String day = addZero(date.get(Calendar.DATE) + "");
		String hh = addZero(date.get(Calendar.HOUR_OF_DAY) + "");
		String mm = addZero(date.get(Calendar.MINUTE) + "");
		String ss = addZero(date.get(Calendar.SECOND) + "");
		return year + month + day + hh + mm + ss;
	}
	/**
	 * 获取SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
	 * @param date
	 * @return
	 */
	public static String getSessionKeyDate(Date date){
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
			return df.format(date);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 获取SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
	 * @param date
	 * @return
	 */
	public static Date getSessionKeyDate(String date){
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
			return df.parse(date);
		} catch (Exception e) {
			return null;
		}
	}

	private static long lastClickTime;
	/**
	 * 解析挑战幀中的时间戳 格式"yyyy/MM/dd HH:mm:ss"
	 * @param str
	 * @return
	 */
	public static String analysisDate(String str){
		try { 
			//DE 07 01 06 01 09 1B 14
			String date = hexToDec(str.substring(2, 4)+str.substring(0, 2));
			date=date +"/"+hexToDec(str.substring(4, 6));
			date=date +"/"+hexToDec(str.substring(6, 8));
			date=date +" "+hexToDec(str.substring(10, 12));
			date=date +":"+hexToDec(str.substring(12, 14));
			date=date +":"+hexToDec(str.substring(14, 16));
			return date;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 将String转化Date 格式"yyyy/MM/dd HH:mm:ss"
	 * @param str
	 * @return
	 */
	public static Date dateFormat(String str){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date= sdf.parse(str);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 将String转化Date 格式"yyyyMMddHHmmss"
	 * @param str
	 * @return
	 */
	public static Date DateFormat(String str){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date= sdf.parse(str);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * "yyyy-MM-dd HH:mm:ss"
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}
	
	public static byte[] subByte(int fistPosion, int b, byte[] bytes) {
		byte[] byt = new byte[b * 2];

		for (int i = 0; i < byt.length; i++) {
			byt[i] = bytes[fistPosion];
			fistPosion++;
		}

		return byt;
	}

	/**
	 * 前补零
	 * 
	 * @param date
	 * @param leng
	 * @return
	 */
	public static String topAddZero(String date, int leng) {
		while (date.length() < leng) {
			date = "0" + date;
		}
		return date;
	}

	/**
	 * 判断时间
	 * 
	 * @return
	 */
	public static boolean isFastDoubleClick(long times) {
		long time = System.currentTimeMillis(); // 1、当前时间
		long timeD = time - lastClickTime; // 2、获得时间差
		Log.e("时间差：", timeD + "");
		if (0 < timeD && timeD < times) { // 3、
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 将相同的卡号相加
	 * 
	 * @param list
	 * @return
	 */
//	public static List<SessionKey> searchCardNumber(List<SessionKey> list) {
//		List<SessionKey> li = new ArrayList<SessionKey>();
//		HashMap<String, SessionKey> map = new HashMap<String, SessionKey>();
//		for (SessionKey bean : list) {
//			if (map.containsKey(bean.getAdminCard())) {
//				SessionKey key = map.get(bean.getAdminCard());
//				key.setTradeLogNumber(key.getTradeLogNumber()
//						+ bean.getTradeLogNumber());
//				key.setTradePhoneNumber(key.getTradePhoneNumber()
//						+ bean.getTradePhoneNumber());
//				key.setOffCheckCountSuccess(key.getOffCheckCountSuccess()
//						+ bean.getOffCheckCountSuccess());
//				key.setOffActivateCountSuccess(key.getOffActivateCountSuccess()
//						+ bean.getOffActivateCountSuccess());
//				key.setOLCheckCountSuccess(key.getOLCheckCountSuccess()
//						+ bean.getOLCheckCountSuccess());
//				key.setOLActivateCountSuccess(key.getOLActivateCountSuccess()
//						+ bean.getOLActivateCountSuccess());
//				key.setOLIndividuationCountSuccess(key
//						.getOLIndividuationCountSuccess()
//						+ bean.getOLIndividuationCountSuccess());
//			} else {
//				map.put(bean.getAdminCard(), bean);
//			}
//
//		}
//		li.clear();
//		li.addAll(map.values());
//		return li;
//	}

	/**
	 * 截串方法
	 * 
	 * @param onSet
	 * @param octet
	 * @param context
	 * @return
	 */
	public static String subString(int onSet, int octet, String context) {
		if (context != null && "".equals(context)) {
			return context.substring(onSet * 2, octet * 2);
		} else {
			return context;
		}
	}

	/**
	 * 发送报文
	 * 
	 * @param context
	 * @return
	 */
	public static byte[] sendBaowen(String context) {
		return EncodingUtil.hex2byte(EncodingUtil.change(context));
	}

	/**
	 * 获取每次的文件名字 yyMMddHHmmss
	 * 
	 * @return
	 */
	public static String getPhoneName() {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
		return df.format(new Date());
	}

//	/**
//	 * 找到最大的序列号
//	 * 
//	 * @return
//	 */
//	public static TradeInfoUploadingRequest searchMaxNum(
//			Map<String, List<TradeInfoUploadingRequest>> TradeInfos) {
//		// 找出最大的时间
//		int min = 0;
//		int max = 0;
//		for (String str : TradeInfos.keySet()) {
//			min = Integer.parseInt(str);
//			if (min > max) {
//				max = min;
//			}
//		}
//
//		List<TradeInfoUploadingRequest> list = TradeInfos.get(max + "");
//		max = 0;
//		TradeInfoUploadingRequest tr = null;
//		for (TradeInfoUploadingRequest tradeInfoUploadingRequest : list) {
//			min = Integer.parseInt(tradeInfoUploadingRequest
//					.getTradingTerminalSerialNumber());
//			if (min > max) {
//				max = min;
//				tr = tradeInfoUploadingRequest;
//			}
//		}
//		return tr;
//	}

	/**
	 * 获取文件名 时间
	 * 
	 * @return
	 */
	public static String getFileName() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
		return df.format(new Date());// new Date()为获取当前系统时间
	}

	/**
	 * 补0
	 * 
	 * @param info
	 * @param number
	 * @return
	 */
	public static String jointZero(String info, int number) {
		String result = "";
		int x = info.length();
		for (int i = x; i < number; i++) {
			result += "0";
		}
		return result + info;
	}

	/**
	 * 拼接上传幀
	 * 
	 * @param strs
	 * @return
	 */
	public static String joint(String... strs) {
		String result = "";
		for (int i = 0; i < strs.length; i++) {
			if (i == strs.length - 1) {
				break;
			}
			result += (strs[i] + ",");
		}
		return result;
	}

	/**
	 * Long类型转换16进制
	 * 
	 * @param date
	 * @param number
	 * @return
	 */
	public static String LongTosix(long date, int number) {
		String six = Long.toHexString(date);
		String zero = "";
		for (int i = 0; i < number; i++) {
			if (six.length() < number) {
				zero += "0";
			}
		}
		return zero + six;
	}

	/**
	 * 车辆颜色
	 * 
	 * @param color
	 * @return
	 */
	public static String vehicleColor(String color) {
		String colo = "";
		try {
			colo = Integer.parseInt(color) + "";
		} catch (Exception e) {

		}
		if ("0".equals(color)) {
			colo = "蓝";
		} else if ("1".equals(color)) {
			colo = "黄";
		} else if ("2".equals(color)) {
			colo = "黑";
		} else if ("3".equals(color)) {
			colo = "白";
		} else if ("4".equals(color)) {
			colo = "绿";
		} else {
			colo = "未定义";
		}
		return colo;
	}

	/**
	 * 判断车辆类型
	 * 
	 * @param type
	 * @return
	 */
	public static String vehicleType(String type) {
		String str = "";
		if ("01".equals(type)) {
			str = "A型车";
		} else if ("02".equals(type)) {
			str = "B型车";
		} else if ("03".equals(type)) {
			str = "C型车";
		} else if ("04".equals(type)) {
			str = "D型车";
		} else if ("05".equals(type)) {
			str = "E型车";
		} else if ("06".equals(type)) {
			str = "F型车";
		} else if ("11".equals(type)) {
			str = "货车A型车";
		} else if ("12".equals(type)) {
			str = "货车B型车";
		} else if ("13".equals(type)) {
			str = "货车C型车";
		} else if ("14".equals(type)) {
			str = "货车D型车";
		} else if ("15".equals(type)) {
			str = "货车E型车";
		} else if ("16".equals(type)) {
			str = "货车F型车";
		} else if ("".equals(type)) {
			str = "未定义";
		} else {
			str = "非法车型";
		}
		return str;
	}

	/**
	 * 检查指纹码是否正确
	 * 
	 * @return
	 */

	public static void checkFing(String fingerprint, String baowen,
			String sessionKey) throws NumberFormatException {
		String str = EncodingUtil.getSignature(baowen, sessionKey).substring(0,
				32);
		if (!fingerprint.toUpperCase().equals(str.toUpperCase())) {
			throw new NumberFormatException("指纹码验证失败");
		}
	}

	/**
	 * 生成指纹吗
	 * 
	 * @param data
	 *            待加密的数据
	 * @param key
	 *            加密使用的key
	 * @return 生成MD5编码的字符串
	 * @throws InvalidKeyException
	 * @throws NoSuchAlgorithmException
	 */
	public static String getSignature(String data1, String key1) {
		try {
			byte[] data = EncodingUtil.hex2byte(EncodingUtil.change(data1));
			byte[] key = EncodingUtil.hex2byte(EncodingUtil.change(key1));
			SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data);
			return EncodingUtil.bytesToHexString(rawHmac);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 生成指纹吗
	 * 
	 * @param data1
	 *            待加密的数据
	 * @param key
	 *            加密使用的key
	 * @return 生成MD5编码的字符串
	 * @throws InvalidKeyException
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] Signature(byte[] bytes, String key1) {
		try {
			byte[] data = bytes;
			byte[] key = EncodingUtil.hex2byte(EncodingUtil.change(key1));
			SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data);
			return rawHmac;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串转ASC码UTF-8
	 * 
	 * @param c
	 * @return
	 */
	public static String getAscii(String c) {
		String s = String.valueOf(c);
		byte[] bytes = s.getBytes();//e4baac413132333435000000
		String dd = "";
		for (int i = 0; i < bytes.length; i++)
			dd += Integer.toHexString(bytes[i] & 0xff);
		return dd;

	}
	/**
	 * 字符串转ASC码 GBK
	 * 
	 * @param c
	 * @return
	 * @throws Exception 
	 */
	public static String getGBKAscii(String c) throws Exception {
			String s = String.valueOf(c);
			byte[] bytes = s.getBytes("GBK");//e4baac413132333435000000
			String dd = "";
			for (int i = 0; i < bytes.length; i++)
				dd += Integer.toHexString(bytes[i] & 0xff);
			return dd;
	}

	/**
	 * 激活OBU返回错误提示
	 * 
	 * @param result
	 * @return
	 */
	public static String getErrorResult(String result) {
		if ("0".equals(result)) {
			result = "true";
		}
		else if("11".equals(result)){
			result  = "PSAM复位失败";
		}
		else if("12".equals(result)){
			result  = "PSAN获取终端机编号错误";
		}
		else if("13".equals(result)){
			result  = "选DF01失败";
		}
		else if("14".equals(result)){
			result  = "PSAM分散";
		}
		else if("15".equals(result)){
			result  = "PSAM解密";
		}
		else if("16".equals(result)){
			result  = "鉴别出错";
		}
		else if("17".equals(result)){
			result  = "算MAC的分散出错";
		}
		else if("18".equals(result)){
			result  = "算MAC出错";
		}
		else if("19".equals(result)){
			result  = "解锁SW错误";
		}
		else if("20".equals(result)){
			result  = "鉴别码核对失败";
		}
		else if("21".equals(result)){
			result  = "SW错误";
		}
		else if("22".equals(result)){
			result  = "计算鉴别码SW错误";
		}
		else if("23".equals(result)){
			result  = "PSAM分散SW错误";
		}
		else if("24".equals(result)){
			result  = "PSAM解密SW错误";
		}
		else if("25".equals(result)){
			result  = "PSAM选DF01，SW错误";
		}
		else if("26".equals(result)){
			result  = "PSAM选DF03，SW错误";
		}
		else if("27".equals(result)){
			result  = "PSAM获取终端机编号，SW错误";
		}
		
		else if("50".equals(result)){
			result  = "PSAM卡获取EF10信息错误";
		}
		else if("51".equals(result)){
			result  = "PSAM卡验证母卡PIN错误";
		}
		else if("52".equals(result)){
			result  = "PSAM选择文件失败";
		}
		else if("53".equals(result)){
			result  = "PSAM卡选择A001错误";
		}
		else if("54".equals(result)){
			result  = "母卡类型错误";
		}
		else if("55".equals(result)){
			result  = "PSAM卡分散密钥失败";
		}
		else if("56".equals(result)){
			result  = "PSAM卡导出主控密钥失败";
		}
		else if("57".equals(result)){
			result  = "PSAM卡导出维护密钥失败";
		}
		else if("58".equals(result)){
			result  = "PSAM卡计算写系统信息MAC";
		}
		else if("59".equals(result)){
			result  = "PSAM卡计算MAC失败";
		}
		else if ("100".equals(result)) {
			result = "寻不到OBU";
		} else if ("101".equals(result)) {
			result = "VST错误";
		} else if ("102".equals(result)) {
			result = "请插卡";
		} else if ("103".equals(result)) {
			result = "标签与IC卡密钥版本不一致";
		} else if ("104".equals(result)) {
			result = "车卡绑定错误";
		} else if ("105".equals(result)) {
			result = "车型错误";
		} else if ("106".equals(result)) {
			result = "输入当前日期错误";
		} else if ("107".equals(result)) {
			result = "输入启用日期错误";
		} else if ("108".equals(result)) {
			result = "输入失效日期错误";
		} else if ("109".equals(result)) {
			result = "比较输入日期错误";
		} else if ("110".equals(result)) {
			result = "不是ETC应用";
		} else if ("111".equals(result)) {
			result = "VST中无系统信息";
		} else if ("112".equals(result)) {
			result = "VST中长度错误";
		} else if ("113".equals(result)) {
			result = "VST中长度错误";
		} else if ("114".equals(result)) {
			result = "VST中的随机数标志错误";
		} else if ("115".equals(result)) {
			result = "BST后收到非VST";
		} else if ("116".equals(result)) {
			result = "读车辆请求超时";
		} else if ("117".equals(result)) {
			result = "Get收到非Get响应";
		} else if ("118".equals(result)) {
			result = "Setmmi超时";
		} else if ("119".equals(result)) {
			result = "Set收到非Set响应";
		} else if ("120".equals(result)) {
			result = "TrasferChannel超时";
		} else if ("121".equals(result)) {
			result = "TransferChannel收到非TransferChannel响应";
		} else if ("122".equals(result)) {
			result = "TrasferChannel中SW错误";
		} else if ("123".equals(result)) {
			result = "取随机数失败";
		} else if ("124".equals(result)) {
			result = "Getrand取随机数失败";
		} else if ("125".equals(result)) {
			result = "Set超时";
		} else if ("126".equals(result)) {
			result = "SET状态错误";
		} else if ("127".equals(result)) {
			result = "有MF1信息，但是CONTINER错误";
		} else if ("128".equals(result)) {
			result = "OBUMAC不相同，非同一个标签";
		} else if ("150".equals(result)){
			result = "OBU版本错误，非16版本";
		}else if ("151".equals(result)){
			result = "OBU区域代码与PSAM卡不一致";
		}else if ("152".equals(result)){
			result = "获取OBU ESAM SN失败";
		}else if ("153".equals(result)){
			result = "OBU选择目录失败";
		}else if ("154".equals(result)){
			result = "OBU选择3F00目录失败";
		}else if ("155".equals(result)){
			result = "OBU选择DF01目录失败";
		}else if ("156".equals(result)){
			result = "获取OBU随机数失败";
		}else if ("157".equals(result)){
			result = "OBU更新密钥失败";
		}else if ("158".equals(result)){
			result = "获取OBU系统信息和随机数失败";
		}else if ("159".equals(result)){
			result = "OBU写系统信息失败";
		}else if ("160".equals(result)){
			result = "获取OBU写数据随机数失败";
		}else if ("161".equals(result)){
			result = "OBU写系统信息或写车辆信息失败";
		}else {
			return "未知错误"+result;
		}
		return result;
	}

	/**
	 * 2个MAP相加
	 * 
	 * @param map1
	 * @param map2
	 * @return
	 */
	public static Map<String, String> addMap(Map<String, String> map1,
			Map<String, String> map2) {
		Iterator<Entry<String, String>> it = map2.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) it.next();
			map1.put(entry.getKey(), entry.getValue()); // 返回与此项对应的键
		}
		return map1;
	}

	/**
	 * 检查报文
	 * 
	 * @param context
	 * @return
	 */
	public static String checkingBaowen(String context) {
		Log.e("接收到的报文：", context);
		int leng = Integer.parseInt(EncodingUtil.hexToDec(
				context.substring(2, 4), 2)) * 2;
		return context.substring(0, leng);
	}

	/**
	 * 验证报文是否完整(如果完整截取返回,不完整返回null)
	 * 
	 * @param context
	 * @return
	 */
	public static String checking(String context) {
		System.err.println("Date:"+context);
		// 判断长度是否正确
		int index = context.indexOf("55AA");
		context = context.substring(index);
		int Length = EncodingUtil.hexStringToInt(context.substring(6, 10)) * 2 + 14;
		context = context.substring(0, Length);
		String bcc = context.substring(context.length() - 2);
		// 截取到发送的数据(总长度-2个字节计算到数据的最后位置)并转换下FE和FF
		String str = context.substring(4, context.length() - 2);
		// 得到比对校验
		String bc = EncodingUtil.yihuo(EncodingUtil.change(str)).toUpperCase();
		// 判断校验是否一致
		if (!bc.equals(bcc)) {
			System.err.println("异或错误："+context);
			System.err.println("异或："+bc);
			throw new NoSuchElementException("异或失败!");
		}
		return context;
	}

	/**
	 * 把时间拆分加上年月日
	 * 
	 * @param time
	 * @return
	 */
	public static String convert(String time) {
		String date = null;
		// 年份
		String str = time.substring(0, 4);
		// 月份
		String year = time.substring(4, 6);
		// 日期
		String day = time.substring(6, 8);
		date = str + "年" + year + "月" + day + "日";
		// 年份
		str = time.substring(8, 12);
		// 月份
		year = time.substring(12, 14);
		// 日期
		day = time.substring(14, 16);
		date += str + "年" + year + "月" + day + "日";
		return date;
	}

	/**
	 * 替换字符传中指定字符(字节完整才会替换)
	 * 
	 * @param context
	 *            字符串
	 * @param type
	 *            FE指定的字符
	 * @param arg
	 *            FE00替换后的字符
	 * @return
	 */
	public static String repliceSend(String context, String type, String arg) {
		int index = 0;
		while (index != -1) {
			index = context.indexOf(type, index);
			if (index > 0 && index % 2 == 0) {
				String filst = context.substring(0, index);
				String last = context.substring(index + 2);
				context = filst + arg + last;
				index += 2;
			} else if (index > 0 && index % 2 != 0) {
				index = context.indexOf(type, index += 2);
			}
		}
		return context;
	}

	/**
	 * 替换字符传中指定字符(字节完整才会替换)
	 * 
	 * @param context
	 *            字符串
	 * @param type
	 *            FE01指定的字符
	 * @param arg
	 *            FE替换后的字符
	 * @return
	 */
	public static String repliceAdopt(String context, String type, String arg) {
		int index = 0;
		while (index != -1) {
			index = context.indexOf(type, index);
			if (index > 0 && index % 2 == 0) {
				String filst = context.substring(0, index);
				String last = context.substring(index + 4);
				context = filst + arg + last;
			} else if (index > 0 && index % 2 != 0) {
				index = context.indexOf(type, index += 2);
			}
		}
		return context;
	}

	/**
	 * 计算指纹码
	 * 
	 * @param context
	 * @return
	 */
	public static String fingerCode(byte[] context) {
		return sha1(context).substring(0, 32);
	}

	/**
	 * 
	 * 修改的
	 * 
	 * @param context
	 * @return
	 */
	public static String subStr(String context, String strs, int type) {
		String sb = "";
		String first = "";
		String str = "";
		switch (type) {
		case 1:
			sb = strs.substring(0, 2);// 第十七字节
			first = context.substring(2);// 第一字节舍弃掉
			return sb + first;
		case 2:
			sb = strs.substring(2, 4);// 第十八字节
			first = context.substring(0, 2);// 第一字节
			str = context.substring(4);// 第二字节
			return first + sb + str;
		case 3:
			sb = strs.substring(4, 6);// 第十九字节
			first = context.substring(0, 4);// 第1-2字节
			str = context.substring(6, 32);// 第三字节
			return first + sb + str;
		case 4:
			sb = strs.substring(6, 8);// 第二十字节
			first = context.substring(0, 6);// 第1-3字节
			str = context.substring(8, 32);// 第三字节
			return first + sb + str;
		}
		return null;
	}

	/**
	 * sha1加密运算
	 * 
	 * @param str
	 * @return
	 */
	public static String sha1(byte[] str) {
		try {
			MessageDigest sha1 = MessageDigest.getInstance("sha1");
			sha1.update(str);
			byte[] hash = sha1.digest();
			return byteArrayToHex(hash);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 把sha1运算后的结果转换字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	public static String byteArrayToHex(byte[] byteArray) {
		// 首先初始化一个字符数组，用来存放每个16进制字符
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}

	/**
	 * 十六进制转换十进制
	 * 
	 * @param str
	 * @return
	 */
	public static String hexToDec(String str) {
		return Long.toString(Long.parseLong(str, 16));
	}

	/**
	 * 十六进制转换十进制
	 * 
	 * @param str
	 * @return
	 */
	public static String hexToDec(String str, int number) {
		String strs = Long.toString(Long.parseLong(str, 16));
		for (int i = 0; i < number; i++) {
			if (strs.length() < number) {
				strs = "0" + strs;
			}
		}
		return strs;
	}

	/**
	 * ascii转字符串
	 * 
	 * @return
	 */
	public static String asciiToString(String value) {
		try {//
			return new String(EncodingUtil.hex2byte(change(value)), "GBK");
		} catch (UnsupportedEncodingException e) {
			return value;
		}
	}
	
	/**
	 * ascii转字符串
	 * 
	 * @return
	 */
	public static String asciiToUTFString(String value) {
		try {//
			return new String(EncodingUtil.hex2byte(change(value)), "utf-8");
		} catch (UnsupportedEncodingException e) {
			return value;
		}
	}

	/**
	 * 处理乱码中文
	 * 
	 * @param context
	 * @return
	 */
	public static String convertEncoding(String temp) {
		try {
			// return new String(temp.getBytes("iso-8859-1"),"UTF-8");
			byte s[] = temp.getBytes("iso-8859-1");
			return new String(s, "GBK");
			// return temp;

		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 将byte转换为一个长度为8的bit（每bit代表一个标识值）
	 * 
	 * @param b
	 * 
	 * @return String
	 */
	public static String getBooleanArray(byte b) {
		boolean[] array = new boolean[8];
		for (int i = 7; i >= 0; i--) { // 对于byte的每bit进行判定
			array[i] = (b & 1) == 1; // 判定byte的最后一位是否为1，若为1，则是true；否则是false
			b = (byte) (b >> 1); // 将byte右移一位

		}
		String str = "";
		for (int i = 0; i < array.length; i++) {
			if (array[i]) {
				str += 1;
			} else {
				str += 0;
			}
		}
		return str;
	}

	/**
	 * 自由截字符串
	 * 
	 * @param context
	 * @param firstIndex
	 * @param lastIndex
	 * @return
	 */
	public static String subString(String context, int firstIndex, int lastIndex) {
		return context.substring(firstIndex, lastIndex);
	}

//	/**
//	 * 终端序列号-1 交易失败
//	 */
//	public static void SetrandomNumber() {
//		if (Integer.parseInt(CodeActivity.TradingNumber) > 0)
//			CodeActivity.TradingNumber = (Integer
//					.parseInt(CodeActivity.TradingNumber) - 1) + "";
//	}

	/**
	 * 生成终端序列号+1
	 * 
	 * @return
	 */
	public static String randomNumber(String str) {

		String number = (Integer.parseInt(str) + 1) + "";
		for (int i = 0; i < 8; i++) {
			if (number.length() < 8) {
				number = "0" + number;
			}
		}
		return number;
	}

	/**
	 * 后补0
	 * 
	 * @param str
	 * @param number
	 * @return
	 */
	public static String addZeor(String str, int number) {
		String result = "";
		for (int i = 0; i < number - str.length(); i++) {
			if (str.length() < number) {
				result = result + "0";
			}
		}
		return str + result;
	}

	/**
	 * 补终端交易序号中的Zero
	 * 
	 * @param str
	 * @param number
	 * @return
	 */
	public static String addZero(String str, int number) {
		String result = str;
		for (int i = 0; i < number - str.length(); i++) {
			if (str.length() < number) {
				result = "0" + result;
			}
		}
		return result;
	}

	/**
	 * Long类型转换Byte数组
	 * 
	 * @param number
	 * @return
	 */
	public static byte[] longToByte(long number) {
		long temp = number;
		byte[] b = new byte[8];
		for (int i = 0; i < b.length; i++) {
			b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位
			temp = temp >> 8;// 向右移8位
		}
		return b;
	}

	/**
	 * 将byte数组转换为 十六进制 string
	 * 
	 * @param bArray
	 * @return
	 */
	public static String bytesToHexString(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2) {
				sb.append(0);
			}
			sb.append(sTemp.toUpperCase());
		}

		return sb.toString();
	}

	public static String bytesToHexString(byte[] bArray, int length) {
		StringBuffer sb = new StringBuffer(length);
		String sTemp;
		for (int i = 0; i < length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2) {
				sb.append(0);
			}
			sb.append(sTemp.toUpperCase());
		}

		return sb.toString();
	}

	public static String sortStr(String cc) {
		StringBuffer stringbuffer = new StringBuffer();
		String sub;
		for (int i = cc.length(); i >= 2; i--) {
			sub = cc.substring(i - 2, i);
			if (!sub.equals("00")) {
				stringbuffer.append(sub);
			}
			i--;
		}
		return stringbuffer.toString();
	}

	/**
	 * 根据长度截取出字符串
	 * 
	 * @param context
	 * @return
	 */
	public static String subLength(String context) {
		int length = hexStringToInt(context.substring(2, 4));
		return context.substring(0, length * 2);
	}

	/**
	 * 异或运算 字符串每16进制字节以空格分开
	 * 
	 * @return
	 */
	public static String yihuo(String str) {
		
		String[] arges = str.split(" ");
		int shijinzhi = Integer.parseInt(arges[0], 16);
		for (int i = 1; i < arges.length; i++) {
			shijinzhi = shijinzhi ^ Integer.parseInt(arges[i], 16);
		}
		String result = Integer.toHexString(shijinzhi);
		if (result.length() < 2) {
			return "0" + result;
		}
		return result.toUpperCase();
	}

	/**
	 * 十进制转换十六进制(位数不够补0)
	 * 
	 * @param num
	 *            十进制参数
	 * @param number
	 *            位数（并非字节数）
	 * @return
	 */
	public static String desToHex(int num, int number) {
		int Num = num;// 要转换的数字

		int length = 32;

		char[] result = new char[length];

		do {

			result[--length] = digits[Num & 15];

			Num >>>= 4;

		} while (Num != 0);
		String str = "";
		for (int i = length; i < result.length; i++) {

			str += result[i];
		}
		if (str.length() < number) {
			String count = "";
			for (int i = str.length(); i < number; i++) {
				count += "0";
			}
			str = new String(count + str);
		}
		return str;
	}

//	/**
//	 * 应答返回码列表
//	 * 
//	 * @author 张鑫
//	 * @param 返回码
//	 * @return "true" / 结果的汉字原因
//	 */
//	public static String result(String strs) {
//		Log.e("收到的报文：", strs + "  ");
//		if (strs.length() <= 6) {
//			return "接收到的报文长度不正确！";
//		}
//		String str = strs.substring(4, 6);
//
//		Log.e("返回应答码：", str + "");
//		if (str.equals("00")) {
//			return "true";
//		} else if (str.equals("01")) {
//			return "服务不可用，请联系系统管理员";
//		} else if (str.equals("02")) {
//			return "会话超时，请重新联机签到";
//		} else if (str.equals("03")) {
//			if (WriteSystemThread.Type.equals("0")) {
//				return "true";
//			} else {
//				return "返回车辆信息有效,但COS指令不可用于写文件";
//			}
//		} else if (str.equals("04")) {
//			return "该CPU卡未发行";
//		} else if (str.equals("05")) {
//			return "该CPU卡已禁用或挂失 ";
//		} else if (str.equals("06")) {
//			return "该车牌号在系统中没有任何记录";
//		} else if (str.equals("07")) {
//			return "该CPU卡内绑定车牌与系统不符，请重新进行CPU卡个性化定制";
//		} else if (str.equals("08")) {
//			return "该标签未发行";
//		} else if (str.equals("09")) {
//			return "该标签已禁用或挂失";
//		} else if (str.equals("0A")) {
//			return "未经过车辆信息的比对检查，请重新进行标签个性化定制";
//		} else if (str.equals("0B")) {
//			return "车辆信息比对失败，请重新进行标签个性化定制";
//		} else if (str.equals("0C")) {
//			return "系统信息比对失败，请重新进行标签个性化定制";
//		} else if (str.equals("0D")) {
//			return "查询失败，未找到相应匹配记录";
//		} else if (str.equals("0E")) {
//			return "该标签合同序列号与卡号绑定关系不符";
//		} else if (str.equals("0F")) {
//			return "交易信息上传失败";
//		} else if (str.equals("10")) {
//			return "有交易信息未上传";
//		} else if (str.equals("80")) {
//			return "指纹码计算不一致！";
//		} else if (str.equals("81")) {
//			return "计算系统MAC失败！！";
//		} else if (str.equals("82")) {
//			return "计算车辆MAC失败！！";
//		} else {
//			// 文档里没有else这种情况
//			return "报文应答码格式不正确";
//		}
//	}

	/**
	 * 10进制转16进制
	 * 
	 * @param num
	 * @return
	 */
	public static String desToHex(int num) {
		int Num = num;// 要转换的数字

		int length = 32;

		char[] result = new char[length];

		do {

			result[--length] = digits[Num & 15];

			Num >>>= 4;

		} while (Num != 0);
		String str = "";
		for (int i = length; i < result.length; i++) {

			str += result[i];
		}
		return str;
	}

	/****************
	 * 16进制字符串转为十进制整数 如 将0E转为十进制的14
	 */
	public static int hexStringToInt(String value) {
		return Integer.valueOf(value, 16);
	}

	// 16进制工具
	static final char digits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',

	'9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * 改变格式 4e2dfc 4e 2d fc
	 * 
	 * @param content
	 * @return
	 */
	public static String change(String content) {
		String str = "";
		for (int i = 0; i < content.length(); i++) {
			if (i % 2 == 0) {
				str += " " + content.substring(i, i + 1);
			} else {
				str += content.substring(i, i + 1);
			}
		}
		return str.trim();
	}

	/**
	 * 把 文本格式的 16进制码 转为 Byte[]
	 * 
	 * @param value
	 * @return
	 */
	public static byte[] hex2byte(String value) {
		String[] str = value.split(" ");
		byte[] b = new byte[str.length];
		for (int i = 0; i < str.length; i++) {

			b[i] = (byte) hexStringToInt(str[i]);

		}
		return b;
	}

	/**
	 * AB指令中当前时间
	 * 
	 * @param date
	 * @return
	 */
	public static String getTime(Calendar date) {
		return date.get(Calendar.YEAR)
				+ EncodingUtil.addZero(date.get(Calendar.MONTH) + 1 + "")
				+ EncodingUtil.addZero(date.get(Calendar.DATE) + "");
	}

	/**
	 * 返回当前时间的要求串
	 * 
	 * @param date
	 * @return
	 */
	public static String getDate(Calendar date) {
		// 年份转16进制(低字节在前,高字节在后)
		String year = desToHex(date.get(Calendar.YEAR));
		year = year.substring(1, 3) + "0" + year.substring(0, 1);
		// 月份转(不够用0补)
		String month = EncodingUtil.desToHex(date.get(Calendar.MONTH) + 1, 2);
		// 日转8进制(不够用0补)
		String day = plus(EncodingUtil.desToHex(date.get(Calendar.DATE)));
		// 星期(星期是1-7,所以减1)
		String week = plus((date.get(Calendar.DAY_OF_WEEK) - 1) + "");
		// 小时(0-23)
		String hour = EncodingUtil.desToHex(date.get(Calendar.HOUR_OF_DAY), 2);
		// 分
		String minute = EncodingUtil.desToHex(date.get(Calendar.MINUTE), 2);
		// 秒
		String second = EncodingUtil.desToHex(date.get(Calendar.SECOND), 2);
		return year + month + day + week + hour + minute + second;
	}

	public static String dbDate(Calendar date) {
		String year = date.get(Calendar.YEAR) + "";
		// 月份转(不够用0补)
		String month = addZero((date.get(Calendar.MONTH) + 1) + "");
		// 日转8进制(不够用0补)
		String day = addZero(date.get(Calendar.DATE) + "");
		return year + month + day;
	}


	/**
	 * 解析时间字符串
	 * 
	 * @param date
	 * @return
	 */
	public static String toDate(String date) {
		date = date.substring(2, 4) + date.substring(0, 2) + date.substring(4);
		String result = "";
		result += sixToTen(date.substring(0, 4));
		result += hexToDec(date.substring(4, 6), 2);
		result += hexToDec(date.substring(6, 8), 2);
		// result += date.substring(8, 10);
		result += hexToDec(date.substring(10, 12), 2);
		result += hexToDec(date.substring(12, 14), 2);
		result += hexToDec(date.substring(14, 16), 2);
		return result;
	}

	/**
	 * 时间前面加0(时分秒)
	 * 
	 * @param value
	 * @return
	 */
	public static String addZero(String value) {
		if (value.length() < 2) {
			return new String("0" + value);
		}
		return value;
	}
	/**
	 * 前面加0
	 * 
	 * @param value
	 * @return
	 */
	public static String inserZero(String value,int number) {
		String str = value;
		while(true){
			if(str.length()<number){
				str = "0"+str;
			}else{
				break;
			}
		}
		return str;
	}
	/**
	 * 八进制转十进制(日期不够两位前面补0)
	 * 
	 * @param value
	 * @return
	 */
	public static String converEightToTen(String value) {
		String str = eightToTen(value);
		if (str.length() < 2) {
			return new String("0" + str);
		}
		return str;
	}

	/**
	 * 减去星期(时分秒)前面的0
	 * 
	 * @param value
	 * @return
	 */
	public static String minusZero(String value) {
		if (value.substring(0, 1).equals("0")) {
			return value.substring(1, 2);
		}
		return value;
	}

	/**
	 * 十六进制转换十进制(会舍弃的前面的0)
	 * 
	 * @param value
	 * @return
	 */
	public static String sixToTen(String value) {
		return Integer.valueOf(value, 16).toString();
	}

	/**
	 * 十六进制转换十进制(会舍弃的前面的0)
	 * 
	 * @param value
	 * @return
	 */
	public static String sixToTen(String value, int count) {
		String str = Integer.valueOf(value, 16).toString();
		str = Integer.valueOf(value, 16).toString();
		String zero = "";
		for (int i = 0; i < count; i++) {
			if (str.length() > count) {
				zero += "0";
			}
		}
		return zero + str;
	}

	/**
	 * 八进制转换10进制
	 * 
	 * @param value
	 * @return
	 */
	public static String eightToTen(String value) {
		return Integer.valueOf(value, 8).toString();
	}

	/**
	 * 字节不够1字节的前面加0
	 * 
	 * @param value
	 * @return
	 */
	public static String plus(String value) {
		if (value.length() < 2) {
			return "0" + value;
		}
		return value;
	}

	/**
	 * 十进制转八进制
	 * 
	 * @param value
	 * @return
	 */
	public static String desToEight(int value) {
		return Integer.toOctalString(value);
	}

	/**
	 * 传入字符串(字节不够前补O)
	 * 
	 * @param str
	 * @param length
	 * @return
	 */
	public static String plusZero(String str, int length) {
		String context = "";
		for (int i = str.length(); i < length; i++) {
			context += "0";
		}
		return context + str;
	}

	/**
	 * MD5加密
	 * @param password
	 * @return
	 */
	public static String getMD5Code(String password) {
		String code = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] byteCode = md.digest(password.getBytes());
			code = bytesToHexString(byteCode);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return code.toLowerCase();
	}

	/**
	 * 获取手机系统型号
	 * @return 0:M10_JL(old)
	 * 	1:module_slm751(new)
	 */
	public static int getSystemType() {
		int nRet = 0;
		String nVer = android.os.Build.VERSION.RELEASE;
		System.err.println("system ver="+nVer);
		if (!TextUtils.isEmpty(nVer)) {
			if (nVer.compareTo("4.4")<0) {
				nRet = 0;
			} else {
				nRet = 1;
			}
		}
		return nRet;
	}

	/**
	 * 检测外置SDCard是否存在
	 * 
	 * @return
	 */
	public static boolean isSDCardExist() {
		String dir = "/storage/sdcard1";
		File f = new File(dir);
		if (f.exists()) {
			String filename = "test";
			File file = new File(dir+"/"+filename);
			if(!file.exists()){
				Log.d("test", "----file create---");
				file.mkdirs();
				if (file.exists()) {
					Log.d("test", "----after create exist---");
					file.delete();
					Log.d("test", "--after create deleted.");
					return true;
				}
			} else {
				Log.d("test", "----file exist---");
				file.delete();
				Log.d("test", "file deleted.");
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取主目录路径
	 * @return
	 */
	public static String getSDCardDirectory() {
		int type = getSystemType();
		if (type == 0) {
			return Environment.getExternalStorageDirectory()+"";
		} else {
			if (isSDCardExist()) {
				return "/storage/sdcard1";
			} else {
				return "/storage/sdcard0";
			}
		}
	}
}
